<template>
  <div class="video-previewer" v-show="isReady">
    <div ref="playerRef" />
  </div>
</template>
<script setup>
import { ref } from "vue";
import DPlayer from "dplayer";
import HLS from "hls.js";
import axios from "axios";
import { ElMessage } from "element-plus";

let player = null
const playerRef = ref(null);
const isReady = ref(false);

const initPlayer = async (url) => {
  let response;
  try {
    response = await axios.get(url);
  } catch (error) {
    ElMessage.error("视频地址不存在");
    return;
  }

  if (!response.data.includes("#EXT-X-ENDLIST")) {
    ElMessage.error("视频地址不存在");
    return;
  }

  player = new DPlayer({
    container: playerRef.value,
    theme: "#FADFA3",
    autoplay: true,
    video: {
      url: url,
      type: "customHls",
      customType: {
        customHls: function (video, player) {
          const hls = new HLS();
          hls.loadSource(video.src);
          hls.attachMedia(video);
        },
      },
    },
  });
  player.on("canplay", () => {
    isReady.value = true;
    player.pause();
  });
};

const play = async (url) => {
  if (!url) return;
  close();
  await initPlayer(url);
};

const close = () => {
  if (player) {
    player.destroy();
  }
  isReady.value = false;
};

defineExpose({
  play,
  close,
});
</script>

<style scoped>
.video-previewer {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.video-container {
  width: 90%;
}
</style>
